/**
 * @param {string} S
 * @return {string}
 */
const removeOuterParentheses = function(S) {
  let resArr = []
  let count = 0
  let strLength = S.length
  for (let i=0; i<=strLength; i++) {
    if (S[i] === "(") {
      if (count > 0) {
        resArr.push(S[i])
      }
      count++
    } else {
      count--
      if (count > 0) {
        resArr.push(S[i])
      }
    }
  }
  return resArr.join("")
};

const removeOuterParentheses2 = function(S) {
  let res = ''
  let count = 0
  for (let v of S) {
    if (v === "(" && count++ > 0) res += v
    if (v === ")" && count-- > 1) res += v
  }
  return res
};


console.log(removeOuterParentheses("(()())(())"));